using System;
using System.Diagnostics;
using flickr.api;
using flickr.api.communication;

namespace FlickrShots.Framework
{
	public class Authenticatr
	{
		private string _frob;
        public string Token
        {
            get { return Preferences.Instance.Token; }
            set { Preferences.Instance.Token = value; }
        }

		private int _authenticationAttempts;
		public int AuthenicationAttempts
		{
			get { return _authenticationAttempts; }
		}

		public void Authenticate()
		{
			if (!IsAuthenticated) 
			{
                _frob = Flickr.Auth.getFrob().Value;

			    Process.Start( Flickr.Connection.GetAuthorizationUrl(_frob) );
				_authenticationAttempts++;
			}
		}

	    public void CompleteAuthentication()
		{
		    if (!IsAuthenticated)
		    {
		        if (_frob != null) 
		        {
                    Auth auth = Flickr.Auth.getToken(_frob);
		            CurrentUser = new User(auth.User);
		            Token = auth.Token;
		        }
		        else
		        {
		            throw new FlickrException(0, "Empty frob");
		        }
		    }
		    else
		    {
                Auth auth = Flickr.Auth.checkToken(Token);
		        CurrentUser = new User(auth.User);   
		    }
		}

	    public static User CurrentUser;

	    public bool IsAuthenticated
		{
			get { return Token != null; }
		}

	    public void ClearAuthentication()
	    {
	        Token = null;
	    }
	}
}
